package boot;


import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.TreeMap;

@RestController
public class HelloWorldController {
    @GetMapping("/")
    public String helloWorld() {
        return "Hello, World!";
    }

    @GetMapping("/send")
    public ResultModel send() throws Exception {
        //组装请求数据   //排序
        TreeMap<String, Object> sortedMap = new TreeMap<>();
        sortedMap.put("age", "1");
        sortedMap.put("name", "9");
        sortedMap.put("class", "2");
        sortedMap.put("class4", "4");
        sortedMap.put("class1", "3");
        sortedMap.put("class5", "5");
        sortedMap.put("class6", "6");
        sortedMap.put("class8", "8");
        sortedMap.put("class7", "7");
        JSONObject sortedJsonObject = new JSONObject(sortedMap);
        System.out.println("字典排序数据:" + sortedJsonObject.toJSONString());
        //B公钥加密
        byte[] encrypt = RSAUtil.encryptByPublicKey(RSAUtil.PUBLICKEYB, sortedJsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
        System.out.println("接收端公钥加密数据:" + Arrays.toString(encrypt));

        // base64加密
        String data = Base64.encode(encrypt);
        System.out.println("base64加密之后数据:" + data);
       // A私钥签名
        String sign = RSAUtil.sign(data, RSAUtil.PRIVATEKEYA);
        System.out.println("发送端私钥加密签名:" + sign);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sign",sign);
        jsonObject.put("data",data);
        this.receive(data,sign);
        return ResultModel.success(jsonObject);
    }


    @GetMapping("/receive")
    public void receive(String data,String sign) throws Exception {
      //验签
        boolean doCheck = RSAUtil.doCheck(data, sign, RSAUtil.PUBLICKEYA);
        System.out.println("发送端公钥验签:" + doCheck);

        byte[] decrypt = RSAUtil.decryptByPrivateKey(RSAUtil.PRIVATEKEYB, data);
        System.out.println("接收端私钥解密后数据:" + new String(decrypt));
        //return ResultModel.success(new String(decrypt));
    }

}

